<?php

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Application\Model\RegionsTable;
use Application\Model\SejourTable;
use Zend\Db\Sql\Expression;
use Application\Service\StringService as StringService;

class RechercheSejourTable
{
    protected $table ='RechercheSejour';
    protected $tableName ='RechercheSejour';
    
    protected $tableGateway;
    protected $stringService;
    protected $regionsTable;
    protected $themesSejourTable;

    public function __construct(TableGateway $tableGateway, ThemesSejourTable $themesSejourTable, RegionsTable $regionsTable, StringService $stringService)
    {
    	$this->tableGateway = $tableGateway;
        $this->stringService = $stringService;
        $this->themesSejourTable = $themesSejourTable;
        $this->regionsTable = $regionsTable;
    }
    
    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select(function(Select $select){
            $select->order('sejourId ASC');
        });
        
        return $resultSet;
    }

    public function fetchAllArray()
    {
        $resultSet = $this->fetchAll();
        $entities = array();
        
        foreach ($resultSet as $row) {
        	$obj = new RechercheSejour();
        	$obj->exchangeArray( (array) $row);
        	$entities[] = $obj;
        }
        
        return $entities;
    }

    public function retournerSejour( $sejourId )
    {

        $resultSet = $this->tableGateway->select(function(Select $select) use($sejourId) {
            $select->where->equalTo('sejourId', $sejourId);
        });

        return $this->toArray($resultSet);
    }

    // on va renommé le nom de l'agence dans les filtres
    public function majEntreeNomAgence(Agence $agence) {

        $this->tableGateway->update( array( 'agenceId' => $agence->id,
                                            'agenceImage' => $agence->imageUrl,
                                            'agenceLibelle' => $agence->libelle), array('agenceId' => $agence->id));
    }

    public function majEntreeSejour(Recherche $sejour, $filtresRechercheSejour ) {

        // print_r($sejour);die;

        $oRechercheSejourExistant = new RechercheSejour();
        $oRechercheSejourExistant = $this->retournerSejour( $sejour->id );
        
        // Enlever les termes inutiles du filtre recherche
        $filtresRechercheSejour = $this->stringService->EnleverCaracteresInutiles ( $filtresRechercheSejour );

        // init objet rechercheSejour
        if($oRechercheSejourExistant == null) {
            $oRechercheSejour = new RechercheSejour();
        }

        $oRechercheSejour->sejourId = $sejour->id;
        $oRechercheSejour->sejourTitre = $sejour->titre;
        $oRechercheSejour->agenceLibelle = $sejour->agenceLibelle;
        $oRechercheSejour->agenceId = $sejour->agenceId;
        $oRechercheSejour->sejourImage = $sejour->imageUrl;
        $oRechercheSejour->activiteId = $sejour->activiteId;
        $oRechercheSejour->activiteLibelle = $sejour->libelleAS;
        $oRechercheSejour->typeSejourLibelle = $sejour->libelleTS;
        $oRechercheSejour->paysId = $sejour->paysId;
        $oRechercheSejour->paysLibelle = $sejour->libellePays;
        $oRechercheSejour->regionId = $sejour->regionId;
        $oRechercheSejour->regionLibelle = $sejour->libelleRegions;
        $oRechercheSejour->sejourDuree = $sejour->duree;
        $oRechercheSejour->niveauPhysique = $sejour->niveauPhysique;
        $oRechercheSejour->niveauTechnique = $sejour->niveauTechnique;
        $oRechercheSejour->niveauConfort = $sejour->niveauConfort;
        $oRechercheSejour->resumeSejour = $sejour->resume;
        $oRechercheSejour->descriptionSejour = $sejour->description;
        $oRechercheSejour->agenceImage = $sejour->agenceImageURL;
        $oRechercheSejour->filtresRecherche = $filtresRechercheSejour;

        if($oRechercheSejourExistant == null) {

            $this->tableGateway->insert( (array) $oRechercheSejour);
        } else {

            $this->tableGateway->update( (array) $oRechercheSejour, array('sejourId' => $sejour->id));
        }
    }

    /* Recherche général et remontée des résultats */
    public function filtrerLesSejours( $filtresRecherche )
    {
        // $filtresRechercheSejour = $this->stringService->EnleverCaracteresInutiles ( $filtresRechercheSejour );
        
        if( count( $filtresRecherche['regions'] ) > 0 ) {
            $listeRegionsPays = $this->regionsTable->initFiltresRegions( $filtresRecherche['regions'] );
        }

        $conditionThematquesActif = false; // car jointure avec la table ThemesSejour
        $conditionRegionActif = false; // car jointure avec la sélection des pays

        $where = new Where();

        foreach ($filtresRecherche['tags'] as $key => $value) {

            $libelleFiltre = $this->stringService->EnleverCaracteresInutiles ( $value );

            $aLibelleFiltre = explode(" ", $libelleFiltre);

            if(count($aLibelleFiltre) > 1) {

                foreach ($aLibelleFiltre as $libkey => $libvalue) {
                    $where->like("filtresRecherche", "%".$libvalue."%");
                }
            } else {

                $where->like("filtresRecherche", "%".$aLibelleFiltre[0]."%");
            }
        }
        
        /* filtre par pays et région*/

        $paysIdArr = array();
        $sousConditionFiltres = '';
        
        if( count($filtresRecherche['regions']) > 0 ) {
            $conditionRegionActif = true;

            $sousConditionFiltres .= ' ( ';

            $cpt = intval(count($filtresRecherche['regions']) - 1 );

            foreach ($listeRegionsPays as $key => $value) {                
                array_push($paysIdArr, $value->idPays);

                $sousConditionFiltres .= 'regionId = ' . $value->idRegions ;

                if($key != $cpt ) {
                    $sousConditionFiltres .= ' OR ' ;
                }
            }

            $sousConditionFiltres .= ' ) ';
        }

        if( count($filtresRecherche['pays']) > 0 ) {
            $cpt=0;

            foreach ($filtresRecherche['pays'] as $key => $value) {

                if( !in_array($value, $paysIdArr) ) {

                    if($cpt == 0 ) {
                        $sousConditionFiltres .=  $sousConditionFiltres != '' ? ' OR ( ' : ' ( ';
                    }

                    $sousConditionFiltres .= 'paysId = ' . $value;
                    $sousConditionFiltres .= ' OR ' ;
                    $cpt++;
                }
            }
            if($cpt>0) {
                $sousConditionFiltres = substr($sousConditionFiltres, 0, -4) . ' ) ';

                if( $conditionRegionActif == true ) {
                    $sousConditionFiltres = ' ( ' . $sousConditionFiltres . ' ) ';
                }
            }
        }

        if( count($filtresRecherche['activites']) > 0 ) {
            $cpt=0;

            foreach ($filtresRecherche['activites'] as $key => $value) {

                if($cpt == 0 ) {
                    $sousConditionFiltres .=  $sousConditionFiltres != '' ? ' AND ( ' : ' ( ';
                }

                $sousConditionFiltres .= 'activiteId = ' . $value;
                $sousConditionFiltres .= ' OR ' ;
                $cpt++;
            }
            if($cpt>0) {
                $sousConditionFiltres = substr($sousConditionFiltres, 0, -4) . ' ) ';
            }
        }

        if( count($filtresRecherche['thematiques']) > 0 ) {
            $cpt=0;
            $conditionThematquesActif = true;// car jointure avec la table ThemesSejour

            foreach ($filtresRecherche['thematiques'] as $key => $value) {

                if($cpt == 0 ) {
                    $sousConditionFiltres .=  $sousConditionFiltres != '' ? ' AND ( ' : ' ( ';
                }

                $sousConditionFiltres .= 'ThemesSejour.themeId = ' . $value;
                $sousConditionFiltres .= ' OR ' ;
                $cpt++;
            }
            if($cpt>0) {
                $sousConditionFiltres = substr($sousConditionFiltres, 0, -4) . ' ) ';
            }
        }

        // $sejoursThemesNonActifs = $this->themesSejourTable->tousLesSejoursAvecThemesNonActifs();
        // foreach ($sejoursThemesNonActifs as $key => $value) {
        //     $where->notEqualTo("sejourId", $value['sejourId']);
        // }

        // echo $sousConditionFiltres;die;

        $resultSet = $this->tableGateway->select(function(Select $select) use($where, $sousConditionFiltres, $conditionThematquesActif) {
            
            if( $conditionThematquesActif == true) {
                $select->join('ThemesSejour', 'RechercheSejour.sejourId = ThemesSejour.sejourId', array('*'), 'inner');
            }

            $select->where($where);

            if( $sousConditionFiltres != '' ) {
                $select->where(array(
                    new \Zend\Db\Sql\Predicate\Expression( ' ( ' . $sousConditionFiltres . ' ) ' )
                ));                
            }

            $select->order('paysLibelle ASC');
            $select->order('regionLibelle ASC');
            $select->order('activiteLibelle ASC');
        });


        /* on ne veut garder que les séjours dont les thèmes sont actifs */
        // foreach ($resultSet as $key => $sejour) {
        //     echo ">> " . $sejour->sejourId. "<br />";
        // }

        return $this->toArray ($resultSet, $forceRetourArray = true);
    }

    public function supprimerEntreeRechercheSejour( $sejourId ) {
        $this->tableGateway->delete(array('sejourId' => $sejourId));
    }

    public function toArray ($resultSet, $forceRetourArray = false)
    {
        $entities = array();
        
        foreach ($resultSet as $row) {
            $obj = new RechercheSejour();
            $obj->exchangeArray( (array) $row);
            $entities[] = $obj;
        }
        
        if(count($entities) == 1 && !$forceRetourArray) {
            return $entities[0];
        }

        return $entities;
    }
}